package com.saver.core.persistence;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Base64;
import android.util.Log;

import com.saver.core.exception.HTTPException;

public abstract class AbstractRestServiceJSON {

	private static final String TAG = "AbstractRestService";
	
	protected JSONArray obtenerJSONArray (String path, HTTPMethod method, Map<String, String> parametros) 
			throws IOException, JSONException, HTTPException {
		
		return obtenerObject (path, method, parametros, new GeneradorObjeto<JSONArray>() {
			@Override
			public JSONArray crearObjeto(String resp) throws JSONException {
				return new JSONArray(resp);
			}
		});
	}

	protected JSONObject obtenerJSONObject (String path, HTTPMethod method, Map<String, String> parametros) 
			throws IOException, JSONException, HTTPException {
		
		return obtenerObject (path, method, parametros, new GeneradorObjeto<JSONObject>() {
			@Override
			public JSONObject crearObjeto(String resp) throws JSONException {
				return new JSONObject(resp);
			}
		});
	}

	protected String obtenerString (String path, HTTPMethod method, Map<String, String> parametros) 
			throws IOException, JSONException, HTTPException {
		
		return obtenerObject (path, method, parametros, new GeneradorObjeto<String>() {
			@Override
			public String crearObjeto(String resp) throws JSONException {
				return resp;
			}
		});
	}

	protected <T> T obtenerObject (String path, HTTPMethod method, 
			Map<String, String> parametros, GeneradorObjeto<T> generadorObjeto) 
			throws IOException, JSONException, HTTPException {

		InputStream inputStream = null;
		HttpURLConnection connection = null;
		T objeto = null;
		
		URL url = new URL(path);
		
		try {
			connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod(method.name());
			connection.setRequestProperty("Connection", "close");
			connection.setDoInput(true);
			connection.setDoOutput(true);
			DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
			outputStream.writeBytes(query(parametros));
			outputStream.flush();
			outputStream.close();
			
			int responseCode = connection.getResponseCode();
	
			if (responseCode == 200) {
				inputStream = connection.getInputStream();
				String consulta = convertirAString(inputStream);
				Log.d(TAG, consulta);
				objeto = generadorObjeto.crearObjeto(consulta);
	
			} else {
				Log.e(TAG, "path: " + path);
				throw new HTTPException("Error de respuesta. Codigo: " + responseCode);
			}
			
		} finally {
			cerrarConexion(inputStream, connection);
		}
		
		return objeto;
	}

	private void cerrarConexion(InputStream inputStream,
			HttpURLConnection connection) throws IOException {
		if (inputStream != null) {
			inputStream.close();
		}
		if (connection != null) {
			connection.disconnect();
		}
	}

	private String convertirAString(InputStream is) throws IOException {
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();

		try {
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line).append("\n");
			}
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				Log.e(TAG, "Error al cerrar el flujo", e);
			}
		}
		return sb.toString();
	}
	
	private String query (Map<String, String> parametros) throws UnsupportedEncodingException {
		for (String key : parametros.keySet()) {
				Log.d(TAG, key + " = " + parametros.get(key));
		}
		
	    StringBuilder result = new StringBuilder();
	    boolean first = true;

	    for (String key : parametros.keySet()) {
	        if (first) {
	            first = false;
	        } else {
	            result.append("&");
	        }

	        result.append(key);
	        result.append("=");
	        result.append(codificar (parametros.get(key)));
	    }
	    Log.d(TAG, result.toString());
	    return result.toString();
	}
	
	private String codificar (String parametro) {
		if (parametro == null) {
			return "";
		} else {
			byte[] data = parametro.getBytes();
			return Base64.encodeToString(data, Base64.DEFAULT).replaceAll("=", "");
		}
	}

	private interface GeneradorObjeto <T> {
		T crearObjeto (String resp) throws JSONException;
	}
	
}
